package studio.raptor.dispatcher.server.service;

import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import studio.raptor.dispatcher.common.constant.EventStatus;
import studio.raptor.dispatcher.server.dao.EventDao;
import studio.raptor.dispatcher.server.entity.EventTrace;
import studio.raptor.dispatcher.server.listeners.ConsumerEventListener;

/**
 * @author jack
 * @since 1.0
 */
@Service
public class RetrySendService {

  private static final Logger log = LoggerFactory.getLogger(RetrySendService.class);


  @Autowired
  ConsumerEventListener eventListener;

  @Autowired
  GraphService graphService;

  @Autowired
  EventDao eventDao;

  @Autowired
  SendService sendService;


  @Scheduled(fixedDelay = 100 * 1000)
  public void retrySend() {
    Set<String> tasks = eventListener.getConsumerTaskMap().keySet();
    for (String task : tasks) {
      String[] codeKindId = task.split("-");
      String code = codeKindId[0];
      Integer kindId = Integer.valueOf(codeKindId[1]);

      Set<String> eventIds = graphService.fetchEvent(code, EventStatus.FAILED, 10);
      if (eventIds.isEmpty()) {
        log.debug("the code :[{}] does not have a failed event", code);
        return;
      }
      List<EventTrace> eventTraces = eventDao.findFailedEvent(code, eventIds, kindId);
      log.info("code:{},kindId:{},retry send eventIds:{}", code, kindId, eventIds);
      sendService.batchSendMessage(eventTraces, true);
    }
  }

}
